import { http } from "@/utils/http";
import type { ApiResponse } from "./user";

export interface PaginationMeta {
  total: number;
  page: number;
  page_size: number;
  pageSize?: number;
  current_page?: number;
  currentPage?: number;
}

export interface PagedList<T> {
  list: T[];
  pagination: PaginationMeta;
}

export interface SysConfigItem {
  id: number;
  config_key: string;
  value_type: "string" | "json" | "bool" | "int" | "decimal" | "float";
  config_value: string | number | boolean | Record<string, any> | Array<any>;
  description: string;
  category: string;
  status: number;
  create_time?: string;
  update_time?: string;
}

export interface SysConfigListResponse {
  list: Array<SysConfigItem>;
  pagination: PaginationMeta;
  categories: Array<string>;
}

export interface CreateSysConfigPayload {
  config_key: string;
  value_type: SysConfigItem["value_type"];
  config_value: string | number | boolean | Record<string, any> | Array<any>;
  category?: string;
  status?: number;
  description?: string;
}

export interface SysMenuItem {
  id: number;
  parent_id: number;
  name: string;
  identifier: string;
  path: string;
  component: string;
  redirect?: string;
  permission_code?: string | null;
  client_type: string;
  sort: number;
  is_visible: number;
  status: number;
  meta?: Record<string, any> | null;
  children?: Array<SysMenuItem>;
  type?: string;
}

export const getSystemConfigList = (params?: Record<string, any>) => {
  return http.request<ApiResponse<SysConfigListResponse>>(
    "get",
    "/system/config",
    { params }
  );
};

export const updateSystemConfig = (
  id: number,
  payload: Partial<SysConfigItem>
) => {
  return http.request<ApiResponse<SysConfigItem>>(
    "put",
    `/system/config/${id}`,
    {
      data: payload
    }
  );
};

export const createSystemConfig = (payload: CreateSysConfigPayload) => {
  return http.request<ApiResponse<SysConfigItem>>("post", "/system/config", {
    data: payload
  });
};

export const removeSystemConfig = (id: number) => {
  return http.request<ApiResponse<boolean>>("delete", `/system/config/${id}`);
};

export const getSystemMenuTree = (params?: Record<string, any>) => {
  return http.request<ApiResponse<{ tree: Array<SysMenuItem> }>>(
    "get",
    "/system/menu",
    { params }
  );
};

export const createSystemMenu = (payload: Partial<SysMenuItem>) => {
  return http.request<ApiResponse<SysMenuItem>>("post", "/system/menu", {
    data: payload
  });
};

export const updateSystemMenu = (id: number, payload: Partial<SysMenuItem>) => {
  return http.request<ApiResponse<SysMenuItem>>("put", `/system/menu/${id}`, {
    data: payload
  });
};

export const removeSystemMenu = (id: number) => {
  return http.request<ApiResponse<boolean>>("delete", `/system/menu/${id}`);
};

export default {
  fetchList: getSystemConfigList,
  update: updateSystemConfig,
  create: createSystemConfig,
  remove: removeSystemConfig
};
